﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using PServiceBus.Core.Runtime;
using System.IO;
using PServiceBus.WebSocket.RPC;
using Phoenix.ReflectionExtensions;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Core.Manager;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Endpoints.WebSocket {
	public partial class Service : ServiceBase {
		private static string _name, _host, _webSocketType;
		private static int _port;
		private static bool _secured;
		private static string _messageBusType;
        private static string _cerfx;
		public Service() {
			InitializeComponent();
			ServiceName = _name;
			Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
		}

		protected override void OnStart(string[] args) {
			DynamicBroker.Broker[_messageBusType].New();
			RPCServer.Start(_host, _port, _secured, _webSocketType, cerfx: _cerfx);
		}

		protected override void OnStop() {
			RPCServer.Stop();
		}

		static void Main(string[] args) {
			if (args.Length < 1)
				throw new ArgumentException("WebSocket RPC Service Require service name to be passed to the command line");
			LoadServiceInfo(String.Join(" ", args));
			ServiceBase[] ServicesToRun;
			ServicesToRun = new ServiceBase[] 
			{ 
				new Service() 
			};
			ServiceBase.Run(ServicesToRun);
		}

		static void LoadServiceInfo(string id) {
            var service = ConfigurationParser.Process("services.xml")
                    .Select(x => x["service"] as Dictionary<string, object>)
                    .Select(x => x.ToDictionary(kv => kv.Key, kv => kv.Value == null ? string.Empty : kv.Value.ToString()))
                    .First(x => x["id"] == id);
			_name = service["name"];
			_port = Convert.ToInt32(service["port"]);
			_host = service["host"];
			_secured = Convert.ToBoolean(service["secured"]);
			_webSocketType = service["webSocketType"];
			_messageBusType = service["messageBusType"];
            _cerfx = service["cerfx"];
            WebSocketConnectionSetting.KeepAlive = Convert.ToInt32(service["keepAlive"]);
			PServiceBus.Services.Web.Configuration.ESBEndpointAddress = service["esbEndpoint"];
			ShellHelper.NetShAddTCPFirewall(_name, _port);
		}
	}
}
